package com.c6906.vdam.monitor.service;

import com.c6906.vdam.monitor.dto.GetindexsByTimesAck;
import com.c6906.vdam.monitor.mapper.CpuUsageMapper;
import com.c6906.vdam.monitor.mapper.DiskUsageMapper;
import com.c6906.vdam.monitor.mapper.ServerDataMapper;
import com.c6906.vdam.monitor.mapper.ServerMapper;
import com.c6906.vdam.monitor.model.CpuUsage;
import com.c6906.vdam.monitor.model.DiskUsage;
import com.c6906.vdam.monitor.model.Server;
import com.c6906.vdam.monitor.model.ServerData;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class MonitorService {

    @Autowired
    private ServerMapper serverMapper;

    @Autowired
    private ServerDataMapper serverDataMapper;

    @Autowired
    private CpuUsageMapper cpuUsageMapper;

    @Autowired
    private DiskUsageMapper diskUsageMapper;
    public  List<String> getAllServers(){
        List<String> allHostNames = serverMapper.findAllHostNames();
        return  allHostNames;
    }

    public  List<CpuUsage> lastCpuUsage(){
        List<CpuUsage> lastCpuUseAge = cpuUsageMapper.findLastCpuUsage();
        return  lastCpuUseAge;
    }

    public void saveData(JsonNode request) {
        String hostName = request.get("hostName").asText();
        long eventTime = request.get("eventTime").asLong();
        long msgSerial = request.get("msgSerial").asLong();
        long memTotal = request.get("memTotal").asLong();
        long memAvailable = request.get("memAvailable").asLong();
        long memUsed = request.get("memUsed").asLong();
        long memFree = request.get("memFree").asLong();
        double memUsedPercent = request.get("memUsedPercent").asDouble();
        double totalCPUUsage = request.get("totalCPUUsage").asDouble();

        // 检查或创建服务器
        Server server = serverMapper.findByHostName(hostName);
        if (server == null) {
            server = new Server();
            server.setHostName(hostName);
            // 设置其他默认值，如果有需要
            serverMapper.insertServer(server);
        }

        // 保存服务器基础数据
        ServerData serverData = new ServerData();
        serverData.setServerId(server.getId());
        serverData.setMsgSerial(msgSerial);
        serverData.setHostName(hostName);
        serverData.setEventTime(new Timestamp(eventTime));
        serverData.setMemTotal(memTotal);
        serverData.setMemAvailable(memAvailable);
        serverData.setMemUsed(memUsed);
        serverData.setMemFree(memFree);
        serverData.setMemUsedPercent(memUsedPercent);
        serverData.setTotalCPUUsage(totalCPUUsage);
        serverDataMapper.insertServerData(serverData);

        // 保存CPU使用数据
        List<CpuUsage> cpuUsages = new ArrayList<>();
        JsonNode coreUsages = request.get("coreUsages");
        if (coreUsages != null && coreUsages.isArray()) {
            for (int i = 0; i < coreUsages.size(); i++) {
                double usagePercent = coreUsages.get(i).asDouble();
                CpuUsage cpuUsage = new CpuUsage();
                cpuUsage.setServerId(server.getId());
                cpuUsage.setMsgSerial(msgSerial);
                cpuUsage.setHostName(hostName);
                cpuUsage.setCpuId(i);
                cpuUsage.setEventTime(new Timestamp(eventTime));
                cpuUsage.setUsagePercent(usagePercent);
                cpuUsageMapper.insertCpuUsage(cpuUsage);
            }
        }

        // 保存磁盘使用数据
        List<DiskUsage> diskUsages = new ArrayList<>();
        JsonNode diskUsagesNode = request.get("diskUsages");
        if (diskUsagesNode != null && diskUsagesNode.isArray()) {
            for (JsonNode diskUsageNode : diskUsagesNode) {
                DiskUsage diskUsage = new DiskUsage();
                diskUsage.setServerId(server.getId());
                diskUsage.setMsgSerial(msgSerial);
                diskUsage.setHostName(hostName);
                diskUsage.setPath(diskUsageNode.get("path").asText());
                diskUsage.setTotal(diskUsageNode.get("total").asDouble());
                diskUsage.setUsed(diskUsageNode.get("used").asDouble());
                diskUsage.setUsagePercent(diskUsageNode.get("percent").asDouble());
                diskUsage.setEventTime(new Timestamp(eventTime));
                diskUsageMapper.insertDiskUsage(diskUsage);
            }
        }
    }

    public List<ServerData> getLastIndex() {

        List<ServerData> latestRecordsByHostNames = serverDataMapper.findLatestRecordsForEachHostName();
        log.info("get all data: {}", latestRecordsByHostNames);

        return latestRecordsByHostNames;
    }

    public GetindexsByTimesAck getindexsByTimes(Timestamp startTimestamp, Timestamp endTimestamp) {
        // 1. 计算开始和结束时间之间的秒数
        long secondsBetween = (endTimestamp.getTime() - startTimestamp.getTime()) / 1000;
        // 2. 计算中间记录数，假设每10秒有一条记录
        long estimatedRecords = secondsBetween / 10;
        // 3. 决定步进值
        int step;
        if (estimatedRecords < 100) {
            step = 1; // 如果记录数小于100，步进为1
        } else {
            // 计算一个适当的步长，100~200都会是1，大于等于200时会变成2
            step = (int)  Math.floor((double) estimatedRecords / 100); // 取中间值作为目标
        }
        // 调用 mapper 方法获取记录
        log.info("find record: {} {} ~ {} {} ",estimatedRecords,step,startTimestamp,endTimestamp);
        List<ServerData> records = serverDataMapper.findRecordsByTimeAndStep(startTimestamp, endTimestamp, step);

        GetindexsByTimesAck ack = new GetindexsByTimesAck();
        ack.setServerData(records);
        return  ack;
    }
}
